import axios from 'axios'

// const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8082'
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || ''

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log(`[API] ${config.method?.toUpperCase()} ${config.url}`)
    return config
  },
  (error) => {
    console.error('[API] Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log(`[API] Response ${response.status} for ${response.config.url}`)
    return response
  },
  (error) => {
    console.error('[API] Response error:', error.response?.data || error.message)
    return Promise.reject(error)
  }
)

// 配置管理
export const configApi = {
  getConfig: () => api.get('/api/config/'),
  updateConfig: (config) => api.post('/api/config/', config),
}

// 任务管理
export const taskApi = {
  getTasks: () => api.get('/api/tasks/'),
  getTask: (filename) => api.get(`/api/tasks/${filename}`),
  createTask: (task) => api.post('/api/tasks/', task),
  updateTask: (filename, task) => api.put(`/api/tasks/${filename}`, task),
  deleteTask: (filename) => api.delete(`/api/tasks/${filename}`),
}

// 套件管理
export const suiteApi = {
  getSuites: () => api.get('/api/suites/'),
  getSuite: (filename) => api.get(`/api/suites/${filename}`),
  createSuite: (suite) => api.post('/api/suites/', suite),
  updateSuite: (filename, suite) => api.put(`/api/suites/${filename}`, suite),
  deleteSuite: (filename) => api.delete(`/api/suites/${filename}`),
}

// 文件上传
export const uploadApi = {
  uploadExcel: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/api/upload-excel/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },
  uploadWord: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/api/upload-word/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },
}

// 执行管理
export const executionApi = {
  runTask: (filename, config = {}) => 
    api.post(`/run/api/run/task/${filename}`, config),
  runSuite: (filename, config = {}) => 
    api.post(`/run/api/run/suite/${filename}`, config),
  getReportLink: (runId) => api.get(`/run/${runId}/report`),
  getPlaybackLink: (runId) => api.get(`/run/${runId}/playback`),
}

// WebSocket 连接管理
export const createWebSocketConnection = (runId) => {
  // const wsUrl = `${API_BASE_URL.replace('http', 'ws')}/run/ws/progress/${runId}`
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  const host = window.location.host;
  const wsUrl = `${protocol}//${host}/run/ws/progress/${runId}`;
  return new WebSocket(wsUrl)
}

export default api
